/**
 * yiqihao(一起好商务股份有限公司) copyright 
 */
package com.p2p.front.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.p2p.front.dal.dao.UserCreditsDao;
import com.p2p.front.dal.model.UserCredits;
import com.p2p.front.enums.UserCreditsType;
import com.p2p.front.service.UserCreditsService;

/**
 *
 * @author leiruiqi@yiqihao.com
 *
 * 2015年1月28日 下午2:35:58
 */
@Service("userCreditsService")
public class UserCreditsServiceImpl implements UserCreditsService {

	@Resource
	private UserCreditsDao userCreditsDao;
	
	@Override
	public boolean create(UserCredits userCredists) {
		if(UserCreditsType.getUserCreditsTypeByName(userCredists.getType())==null){
			return false;
		}
		userCreditsDao.create(userCredists);
		return true;
	}

	@Override
	public boolean create(String uid, UserCreditsType type, Long value) {
		UserCredits userCredits = new UserCredits();
		userCredits.setUid(uid);
		userCredits.setType(type.name());
		userCredits.setValue(value);
		return create(userCredits);
	}
	
	@Override
	public UserCredits getByUserAndTypeAutoCreate(String uid, UserCreditsType type) {
		if(StringUtils.isBlank(uid)){
			return null;
		}
		UserCredits userCredits = userCreditsDao.getByUserAndType(uid, type.name());
		if(userCredits==null){
			this.create(uid,type,0l);
			userCredits = userCreditsDao.getByUserAndType(uid, type.name());
		}
		return userCredits;
	}
	
	@Override
	public UserCredits getByUserAndType(String uid, UserCreditsType type) {
		UserCredits userCredits = userCreditsDao.getByUserAndType(uid, type.name());
		return userCredits;
	}


	@Override
	public boolean addValue(String uid, UserCreditsType type, Long addValue) {
		return 1==userCreditsDao.addValue(uid, type.name(), addValue);
	}

	@Override
	public boolean subValue(String uid, UserCreditsType type, Long subValue) {
		return 1==userCreditsDao.subValue(uid, type.name(), subValue);
	}

	@Override
	public Map<String,UserCredits> queryByTypeAndUids(List<String> userIds, UserCreditsType type) {
		List<UserCredits> list = userCreditsDao.queryByTypeAndUids(type.name(), userIds);
		Map<String,UserCredits> map = new HashMap<String,UserCredits>();
		for(UserCredits userCredits:list){
			map.put(userCredits.getUid(), userCredits);
		}
		return map;
	}

	@Override
	public List<UserCredits> queryTopByType(UserCreditsType type, Integer top) {
		return userCreditsDao.queryTopByType(type.name(), top);
	}

	
	

}
